﻿using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Sustainalytics.Synchronization.Validation.Validators;

namespace Sustainalytics.Synchronization.Validation.Handlers.Common
{
    public interface IHandler
    {
        Task ForEachElementsAsync(Action<ValidationResult> validationCallback);
    }

    public interface IHandler<in TU, TK> : IHandler
    {
        Task<TK> GetReferenceElementAsync(TU validatedEntity);
    }

    public class SyncLogHandlerDecorator : IHandler
    {
        private readonly Func<IHandler> handlerFactory;

        private Action<string> syncLoggingAction;

        public SyncLogHandlerDecorator(Func<IHandler> handlerFactory)
        {
            this.handlerFactory = handlerFactory;
        }

        public void SetLoggingOutput(Action<string> action)
        {
            syncLoggingAction = action;
        }

        public async Task ForEachElementsAsync(Action<ValidationResult> validationCallback)
        {
            var decoratedHandler = handlerFactory();
            syncLoggingAction.Invoke("START - " + decoratedHandler.GetType().FullName);
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            await decoratedHandler.ForEachElementsAsync(validationCallback).ConfigureAwait(false);
            stopwatch.Stop();
            syncLoggingAction.Invoke("FINISHED - " + decoratedHandler.GetType().FullName + " in " + stopwatch.Elapsed);
        }
    }
}